package cn.regexp.websocket.ws;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Regexpei
 * @date 2024/7/6 15:09
 * @description websocket服务端
 */
@Slf4j
@Setter
@Getter
@Component
@ServerEndpoint("/{uuid}")
public class WebSocketServer {

    private Session session;

    public static ConcurrentHashMap<String, WebSocketServer> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("uuid") String uuid) {
        log.debug("Client open: {}", uuid);
        this.session = session;
        clients.put(uuid, this);
    }

    @OnClose
    public void onClose(@PathParam("uuid") String uuid) {
        clients.remove(uuid);
    }


    @OnError
    public void onError(Throwable error) {
        log.error("Websocket connect error, message: {}", error.getMessage(), error);
    }
}